package com.surazezhu.xunwuproject.security;

import com.surazezhu.xunwuproject.entity.User;
import com.surazezhu.xunwuproject.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
/**
 * 身份验证 提供auth provider/从数据库 读取admin数据
 * @author:SuarezZhu Date:2018/8/8 Time:18:59
 */
public class AuthProvider implements AuthenticationProvider {
    @Autowired
    private IUserService userService;

    private final Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //认证的姓名密码。在桌面输入的
        String userName = authentication.getName();
        String inputPassword = (String) authentication.getCredentials();

        User user = userService.findUserByName(userName);
        if (user == null) {
            throw new AuthenticationCredentialsNotFoundException("authError&usernull");//Authentication（认证） Credentials资格
        }

        if (this.passwordEncoder.isPasswordValid(user.getPassword(), inputPassword, user.getId())) {//valid有效的，bug解决10点50分，md5加密的问题 数据库里的密码是经过加密的= =
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());//如果密码相等，那么将admin或者user属性赋值给user，用于用户拦截

        }

        throw new BadCredentialsException("authError&passworderror");

    }
    //支持所有的认证类

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}

